<?
    require_once("config.php");
    
    if (!AuthManager::CheckPermissions(AuthConstants::ADMINISTRATORS)) {
        Functions::PrintHeader("ERROR");
        ErrorMessage::Show("Permissions Error","Sorry, you don't have permission to access this resource.");
        Functions::PrintFooter();
        exit;
    }
    
    $menu = new Menu("Tasks");
    $menu->AddItem(new MenuItem("Manually Create Guest","guest.php?action=manual"));
    $menu->AddItem(new MenuItem("View All Guests","admin_guest.php?action=list"));
    
    function approve_all($ids) {
        foreach ($ids as $id) {
            $authlevel = $_POST['override_auth_' . $id];
            $arr = array('approved' => 1, 'override_auth' => $authlevel);
            if (empty($authlevel)) unset($arr['override_auth']);
            $query = QueryTools::CreateQuery($arr,'guests','update',$id);
            
            // Send E-Mail or display password information so the admin can send it
            if (MailManager::MailEnabled()) {
                if (MailManager::SendGuestAccountConfirmation($id)) {
                    DBM::Query($query);
                    SuccessMessage::Show("Account Approved","A confirmation email has been sent to the E-Mail address on file.  <a href='admin_guest.php'>Click here to go back to the guest requests.</a>");
                    
                    // once this is done we dont need the plain text password anymore:
                    DBM::Execute("UPDATE guests SET password_plaintext = '' WHERE id=$id;");
                }
                else {
                    ErrorMessage::Show("Error Sending Mail","The account was not approved because the mail server could not be contacted.  If you would like to disable outgoing mail, you can do so <a href='admin_settings.php'>here</a>");
                }
            }
            else {
                $message = SettingManager::GetSetting("Guest accounts confirmation email");
                $message = DynaText::BindFromEnv($message);
                $message = DynaText::BindFromDatabase($message,"guests",$id);
                $message = DynaText::ParseForMail($message);
                SuccessMessage::Show("Account Approved","<code>" . str_replace(array("    ","\n"),array(str_repeat("&nbsp;",4),"<br>"),$message) . "</code><br><br><b>The E-Mail message could not be sent but the account was approved.</b>");
            }
        }
    }
    
    
    if (isset($_GET['approval'])) {
        Functions::PrintHeader("Account Requests Received");
        
        approve_all($_GET['approval']);
        
        Functions::PrintFooter();
    } 
    else if ($_GET['action'] == "approve") {
        Functions::PrintHeader("Account Request Received");
        
        approve_all(array($_GET['id']));

        Functions::PrintFooter();
    }
    else if ($_GET['action'] == "deny") { 
        $query = "DELETE FROM guests WHERE id=$_GET[id];";
        DBM::Query($query);
        
        header("Location: admin_guest.php");
    }
    else if ($_GET['action'] == "list") {
        MenuManager::AddMenu("View All Guests",$menu);
        
        Functions::PrintHeader("View All Guests");
        $guests = DBM::FetchAllRows("SELECT * FROM guests ORDER BY name ASC;");
        
        echo "<table class='wide cgltable'>";
        echo "<thead><tr>
                <th>ID</th>
                <th>Name</th>
                <th>E-Mail</th>
                <th>Expires On</th>
                <th>Account Type</th>
                <th>&nbsp;</th>
            </tr></thead>";
            
        $acct_types = array('',"Guest","Student","Landlord","Administrator");
        foreach ($guests as $guest) {
            $guestcq = "SELECT * FROM guests WHERE email LIKE '$guest[email]';";
                
            if (DBM::CountRows($guestcq) > 1)
                $color = "red";
            else
                $color = "black";

            echo "<tr>
                    <td>$guest[id] </td>
                    <td>$guest[name] </td>
                    <td>".($color == "red" ? "<span style='font-weight:bold; color:red;'>$guest[email]</span>" : $guest['email']) . "</td>
                    <td>" . ($guest['expires'] > 0 ? date("M d, Y",$guest['expires']) : "Never") . "</td>
                    <td>" . $acct_types[$guest['override_auth']] . "</td>
                    <td><a href='guest.php?id=$guest[id]'>edit</a> | <a href='admin_guest.php?action=delete&id=$guest[id]'>delete</a></td>
                </tr>";
        }
        echo "</table>";

        echo "** E-Mail addresses in red already have an acconut in the system.<br />";
        Functions::PrintFooter();
    }
    else if ($_GET['action'] == "delete") {
    	$query = "DELETE FROM guests WHERE id=$_GET[id]";
    	DBM::Execute($query);
    	header("Location: admin_guest.php?action=list");
    }
    else {
        MenuManager::AddMenu("Confirm Guest Requests",$menu);
        
        Functions::PrintHeader("Confirm Guest Requests");
        $rows = DBM::FetchAllRows("SELECT * FROM `guests` WHERE `approved`='0' ORDER BY `created` ASC;");
        if (count($rows) > 0) {
            ?>
			<form action='admin_guest.php' method='get' name='chkform'>
            <table class='cgltable wide'>
            <thead>
                <tr>
					<th></th>
                    <th>Name</th>
                    <th>E-Mail</th>
                    <th>RIN</th>
                    <th>Request Type</th>
                    <th>Requested On</th>
                    <th>Actions</th>
                </tr>
            </thead>
			<?
			$build = array();
			$acct_types = array('',"Guest","Student","Landlord","Administrator");
			
            foreach ($rows as $index => $row) {
                $guestcq = "SELECT * FROM guests WHERE email LIKE '$row[email]';";
                $color = "black";
                if (DBM::CountRows($guestcq) > 1) {
                    $color = "red";
                }
                else $color = "black";
                
				array_push($build,$row['id']);
                echo "<tr>
					<td><input type='checkbox' name='approval[]' id='approve-$row[id]' value='$row[id]' /></td>
                    <td>$row[name]</td>
                    <td>" . ($color == "red" ? "<span style='font-weight:bold; color:red;'>$row[email]</span>" : $row['email']) . "</td>
                    <td>$row[rin]</td>
                    <td>";
                    
                    echo "<select name='override_auth_$row[id]'>";
                    foreach ($acct_types as $num => $text) {
                        if ($num == 0) continue;
                        echo "<option value='$num' " . ($row['override_auth'] == $num ? " selected='selected'" : "") . ">$text</option>";
                    }
                    echo "</select>";
                    
                    echo "</td>
                    <td>" . date("M d, Y",$row['created']) . "</td>
                    <td><a href='admin_guest.php?action=approve&id=$row[id]'>approve</a> | <a href='admin_guest.php?action=deny&id=$row[id]'>deny</a></td>
                </tr>";
            }
            echo "<tfoot><tr><td colspan='7'><a href='#' onclick='javascript:selectAllBoxes();'>Select All</a>&nbsp;|&nbsp;<a href='#' onclick='javascript:clearAllBoxes();'>Clear Selection</a>&nbsp;<input type='submit' value='Approve Selected' /></td></tr></tfoot></table></form>";
			echo "<script type='text/javascript'>function $(e){ return document.getElementById(e); } function selectAllBoxes(){";
			foreach ($build as $key) echo "$('approve-$key').checked=true;"; 
			echo "} function clearAllBoxes(){";
			foreach ($build as $key) echo "$('approve-$key').checked=false;";
			echo "} </script>";
        }
        else {
            InfoMessage::Show("No Pending Requests","There are currently no pending guest account requests.");
        }
        Functions::PrintFooter();
    }
?>
